package com.nowcoder;

/**
 * 链表翻转
 */
public class LinkedListReverse {

    public static ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode newHead = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = newHead;
            newHead = head;
            head = next;
        }
        return newHead;
    }

    static class ListNode implements Cloneable {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        ListNode node1 = new ListNode(1);
        ListNode node2 = (ListNode) node1.clone();
        ListNode node3 = (ListNode) node1.clone();
        node2.val = 2;
        node1.next = node2;
        node3.val = 3;
        node2.next = node3;
        ListNode node = node1;
        while (node != null) {
            System.out.println("翻转前：" + node.val);
            node = node.next;
        }
        ListNode rnode = reverseList(node1);
        while (rnode != null) {
            System.out.println("翻转后：" + rnode.val);
            rnode = rnode.next;
        }
    }

}
